# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '17/10/2024'
    comment: 服务流程
"""
from fastapi import APIRouter, Query, Request, Body

from config import Config
from project.core.function import json_response
from project.lib.decorator import api_common, exec_duration
from project.model.basic import Selector, InvoiceType, TitleType, Resource
from project.service.record import RecordService
from project.lib.common import Global


record_router = APIRouter(prefix='/c', tags=['cariabot.record'])


@record_router.post('/flow/record/submit', summary='提交服务记录', include_in_schema=False)
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), dev_info=True)
@exec_duration(add_return=True)
async def do_flow_record_submit(request: Request,
                                flow_code: str = Body(..., title='服务流程编号'),
                                selectors: list[Selector] = Body([], title='节点选择信息'),
                                session=None,
                                device=None):
    """
    **desc**: 提交服务流程

    **url**: http(s)://{0}.udicaria.com/c/flow/record/submit

    **method**: POST

        <body>:
            flow_code: 服务流程编号
            selectors:[
                {
                    node_code: 节点编号
                    items: [
                        {
                            title: 项目名
                            image: 项目图片
                            count: 项目数量
                            price: 项目单价
                            spec: [
                                {
                                    title: 规格名称
                                    items: 选择规格列表
                                }
                            ]规格信息
                            date: 选择日期 today(今日)/tomorrow(明日)/after_tomorrow(后日)
                            group_title: 分组名

                        ]
                    ]
                }
            ] 选择的节点信息

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                id: 服务记录id
                code: 服务记录编号
            }
            exec_time: 接口后端处理时长
        }
    """
    flow_record = await RecordService.do_flow_record_submit(session, flow_code, device=device, selectors=selectors)

    return json_response(data=flow_record.dict('id', 'code'))


@record_router.post('/flow/record/invoice/submit', summary='提交发票')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def do_flow_invoice_submit(request: Request,
                                 flow_code: str = Body(..., title='服务流程编号'),
                                 dev_id: str = Body(..., title='设备id'),
                                 room_number: str = Body(..., title='房间号'),
                                 invoice_type: InvoiceType.enums(fixed=Global.count()) = Body(..., title='发票类型', description='electronic(电子发票)/paper(纸质发票)'),
                                 title_type: TitleType.enums(fixed=Global.count()) = Body(..., title='抬头类型', description='enterprise(企业单位)/individual(个人/非企业单位)'),
                                 invoice_title: str = Body(..., title='发票抬头'),
                                 tax_number: str = Body('', title='税号'),
                                 email: str = Body('', title='邮箱'),
                                 bank_name: str = Body('', title='开户银行'),
                                 bank_account: str = Body('', title='银行账号'),
                                 company_address: str = Body('', title='公司地址'),
                                 company_phone: str = Body('', title='公司电话'),
                                 selectors: list[Selector] = Body([], title='节点选择信息'),
                                 session=None,
                                 body_params=None):
    """
    **desc**: 提交发票

    **url**: http(s)://{0}.udicaria.com/c/flow/record/invoice/submit

    **method**: POST

        <body>:
            flow_code: 服务流程编号
            dev_id: 设备id号
            room_number: 房间号
            invoice_type: 发票类型 electronic(电子发票)/paper(纸质发票)
            title_type: 抬头类型 enterprise(企业单位)/individual(个人/非企业单位)
            invoice_title: 发票抬头
            tax_number: 税号
            email: 邮箱
            bank_name: 开户银行
            bank_account: 银行账号
            company_address: 公司地址
            company_phone: 公司电话

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    flow_record = await RecordService.do_flow_invoice_submit(session, body_params)

    return json_response(data=flow_record.dict('id', 'code'))


@record_router.post('/flow/record/cancel', summary='取消服务记录')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), dev_info=True)
@exec_duration(add_return=True)
async def do_flow_cancel(request: Request,
                         flow_code: str = Body('', title='服务流程编号'),
                         code: str = Body('', title='服务记录编号'),
                         session=None, device=None):
    """
    **desc**: 服务记录取消

    **url**: http(s)://{0}.udicaria.com.udicaria.com/c/flow/record/cancel

    **method**: POST

        <body>:
            code: 服务记录编号
            flow_code: 服务流程编号

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    await RecordService.do_flow_record_cancel(session, code=code, flow_code=flow_code, dev_id=device.dev_id)

    return json_response()


@record_router.post('/flow/record/resource/submit', summary='提交图片/视频资源')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def do_flow_resource_submit(request: Request,
                                  flow_code: str = Body(..., title='服务流程编号'),
                                  dev_id: str = Body(..., title='设备id'),
                                  resource: Resource = Body({}, title=''),
                                  session=None,
                                  body_params=None):
    """
    **desc**: 提交服务记录图片/视频资源

    **url**: http(s)://{0}.udicaria.com/c/flow/record/resource/submit

    **method**: POST

        <body>:
            flow_code: 服务流程编号
            dev_id: 设备id号
            resource: {
                resource_paths: 资源路径列表
                description: 资源描述
            }

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    flow_record = await RecordService.do_flow_resource_submit(session, body_params)

    return json_response(data=flow_record.dict('id', 'code'))


@record_router.get('/flow/record/list', summary='服务记录列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), dev_info=True)
@exec_duration(add_return=True)
async def get_flow_record_list(request: Request, session=None, device=None):
    """
    **desc**: 服务记录列表

    **url**: http(s)://{0}.udicaria.com/c/flow/record/list

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: [
                {
                    code: 服务记录编号
                    icon: 服务图标
                    flow_name: 服务名称
                    flow_process_name: 当前节点
                    status: 当前服务状态 init(待完成)/success(已完成)/cancel(已取消)
                    status_list: 服务状态列表
                    flow_time: {
                        date: 服务日期 today(今日)/tomorrow(明日)/after_tomorrow(后日)
                        time: 服务时间
                    } 预计服务时间
                    appoint_time: 预约时间 - flow_time的TIMESTAMP格式
                    is_timeout: 是否超时
                    update_time: 更新时间
                }
            ]
            exec_time: 接口后端处理时长
        }
    """
    data = await RecordService.get_flow_record_list(session, device=device)

    return json_response(data=data)


@record_router.get('/flow/record/detail', summary='服务记录详情')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),), dev_info=True)
@exec_duration(add_return=True)
async def get_flow_record_detail(request: Request, code: str = Query(..., title='服务记录编号'), session=None, device=None):
    """
    **desc**: 服务记录详情

    **url**: http(s)://{0}.udicaria.com/c/flow/record/detail

    **method**: GET

    **params**:

        <query>:
            code: 服务记录编号

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                code: 服务记录编号
                icon: 服务图标
                flow_name: 服务流程名称
                flow_process_name: 当前节点
                status: 当前服务状态 init(待完成)/success(已完成)/cancel(已取消)
                room_no: 房间号
                status_list: 服务状态列表
                flow_time: {
                    data: 服务日期 today(今日)/tomorrow(明日)/after_tomorrow(后日)
                    time: 服务时间
                } 预计服务时间
                appoint_time: 预约时间 - flow_time的TIMESTAMP格式
                is_timeout: 是否超时
                content: [
                    {
                        title: 商品名
                        image: 商品图片
                        count: 商品数量
                        price: 商品单价
                        spec: [] 规格信息 [{"title": xxx, "items": [xxx, xxx, xxx]}, {"title": xxx, "items": [xxx, xxx, xxx]}]
                        item_type: 节点类型 list_image(图片列表)/list_text(文字列表)
                        node_type: 页面节点类型
                    }
                    ...
                ] 服务内容
            }
            exec_time: 接口后端处理时长
        }
    """
    data = await RecordService.get_flow_record_detail_simplify(session, device=device, code=code)

    return json_response(data=data)


@record_router.get('/flow/record/send_sms/test', summary='测试发送短信')
@api_common()
@exec_duration(add_return=True)
async def get_flow_record_send_sms_test(request: Request, session=None, device=None):
    """
    :param request:
    :param code:
    :param session:
    :param device:
    :return:
    """
    await RecordService.send_sms(session, 231, sms_type='cancel')

    return json_response()
